package org.example;

import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Random;

public class MySQLRedisDemo {
    //mysql连接
    private Connection conn;
    //jedis连接
    private Jedis jedis;
    private void Init(){
        String mySqlDriver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/redisdemo";
        try{
           Class.forName(mySqlDriver);
           conn= DriverManager.getConnection(url,"root","");
           jedis = new Jedis("localhost",6379);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public MySQLRedisDemo(){
        Init();
    }
    public void Close(){
        try {
            if(jedis != null && !jedis.isConnected()){jedis.close();}
        }
        catch(Exception ex1){ex1.printStackTrace();}
        try {
            if(conn!=null && !conn.isClosed()){conn.close();}
        }
        catch(Exception ex2){ex2.printStackTrace();}
    }
    //根据学生id查询学生信息，如果在redis中，则直接返回
    //如果不在redis中，则直接查询mysql，同时对该数据进行缓存
    public Student getStudentById(int id){
        String key="Stu:"+id;
        Student stu=new Student();
        Random rnd=new Random();
        //在redis中查找该key对应的值
        if (jedis.exists(key)){
            System.out.println("ID:"+key+"存在于redis中");
            //读取redis中查找该key对应的值
            List<String> list=jedis.lrange(key,0,2);
            stu.setId(id);
            stu.setName(list.get(0));
            stu.setAge(Integer.parseInt(list.get(1)));
            stu.setScore(Float.parseFloat(list.get(2)));
            return stu;
        }
        else{
            System.out.println("ID:"+key+"不存在于redis中");
            PreparedStatement ps=null;
            try{
                ps=conn.prepareStatement("select * from student where id=?");
                ps.setInt(1,id);//传递参数
                ResultSet rs=ps.executeQuery();//执行参数
                if (rs.next()){
                    System.out.println("ID:"+key+"存在于redis中");
                    stu.setId(id);
                    String name = rs.getString("name");
                    stu.setName(name);
                    int age = rs.getInt("age");
                    stu.setAge(age);
                    float score = rs.getFloat("score");
                    stu.setScore(score);
                    //将查到的数据进行redis缓存
                    jedis.rpush(key,name,Integer.valueOf(age).toString(),Float.valueOf(score).toString());
                    jedis.expire(key,60*60+rnd.nextInt(6));//设置有效期，防止内存溢出,加随机数防止缓存雪崩
                    return stu;
                }else {
                    System.out.println("ID:"+key+"存在于redis中");
                    //缓存不存在的值，防止缓存穿透
                    jedis.rpush(key,"null","0","0");
                    jedis.expire(key,60*60+rnd.nextInt(6));//设置有效期，防止内存溢出,加随机数防止缓存雪崩
                    return null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
